package me.skyun.androidarch.common;

import android.graphics.Bitmap;
import android.support.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.List;

/**
 * Created by skyun on 17/8/23.
 */

public class DataInputStreamEx extends DataInputStream {

    /**
     * Creates a DataInputStream that uses the specified
     * underlying InputStream.
     *
     * @param in the specified input stream
     */
    public DataInputStreamEx(@NonNull InputStream in) {
        super(in);
    }

    public String readString() throws IOException {
        int strLen = readInt();
        byte[] bytes = Utils.inputStream2Bytes(this, strLen);
        String s = new String(bytes);
        return s;
    }

    public Bitmap readBitmap() throws IOException {
        int imageLen = readInt();
        byte[] bytes = Utils.inputStream2Bytes(this, imageLen);
        Bitmap bitmap = Utils.bytes2Bitmap(bytes);
        return bitmap;
    }

    public <T> T readEnum(Class<T> cls) throws IOException {
        try {
            String s = readString();
            Method valueOfMethod = cls.getMethod("valueOf", String.class);
            T value = (T) valueOfMethod.invoke(cls, s);
            return value;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
        return null;
    }

    public Class readClass() throws IOException, ClassNotFoundException {
        String clsName = readString();
        Class cls = Class.forName(clsName);
        return cls;
    }

    public Object readObject() throws IOException, ClassNotFoundException {
        Class cls = Class.forName(readString());
        String json = readString();
        Object obj = new Gson().fromJson(json, cls);
        return obj;
    }

    public List readList() throws IOException, ClassNotFoundException {
        Class cls = readClass();
        String json = readString();
        Type type = TypeToken.getParameterized(List.class, cls).getType();
        List obj = new Gson().fromJson(json, type);
        return obj;
    }
}
